package com.enlighten.aio.api;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import com.alibaba.fastjson.JSON;
import com.x.share.api.controller.BaseController;
import com.x.share.api.controller.CmsRoleCheck;
import com.x.share.mid.model.AToken;
import com.x.share.mid.model.UToken;
import com.x.share.mid.prop.ShareProperties;

@Component
@Aspect
public class ApiControllerAop extends BaseController {

	Logger logger = LoggerFactory.getLogger(ApiControllerAop.class);

	@Resource
	ShareProperties shareProps;

	@Pointcut("execution(* com.enlighten.aio.*.controller..*.*(..))")
	public void executeService() {

	}

	@Around("executeService()")
	public Object doAroundAdvice(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
		RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = (HttpServletRequest) requestAttributes
				.resolveReference(RequestAttributes.REFERENCE_REQUEST);
		String uri = request.getRequestURI();
		if (uri.equals("/api/auth")) {
			return proceedingJoinPoint.proceed();
		}
		String appId = request.getHeader("appId");
		String accessToken = request.getHeader("atk");
		if (StringUtils.isBlank(appId) || StringUtils.isBlank(accessToken)) {
			logger.info(">>>> invalid request url(with out appId or atk in request header): {}",
					request.getRequestURL().toString());
			return fail("请联系管理员申请api访问权限!");
		}
		MethodSignature sign = (MethodSignature) proceedingJoinPoint.getSignature();
		CmsRoleCheck anno = sign.getMethod().getAnnotation(CmsRoleCheck.class);
		if (anno != null) {
			String userToken = request.getHeader("utk");
			logger.info(">>>> verify user token: {}", userToken);
			UToken.from(userToken, shareProps.getAeskey());
		}
		try {
			AToken atk = AToken.from(accessToken, shareProps.getAeskey());
			if (atk != null && atk.getAppId().equals(appId)) {
				return proceedingJoinPoint.proceed();
			} else {
				logger.info(">>>> request url: {}", request.getRequestURL().toString());
				logger.warn("!!!! invalid request: appId={}, access token={}", appId, JSON.toJSONString(atk));
				return fail("非法的访问token!");
			}
		} catch (Throwable e) {
			throw e;
		}
	}
}